package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    public List<ShopType> queryList() {

        String redisKey = RedisConstants.CACHE_SHOP_TYPE_KEY;
        List<String> typeRange = stringRedisTemplate.opsForList().range(redisKey, 0, -1);
        if(typeRange!=null && !typeRange.isEmpty()){
            return typeRange.stream()
                    .map(type -> JSONUtil.toBean(type, ShopType.class))
                    .collect(Collectors.toList());
        }

        //redis中不存在，存储并设计超时时间
        List<ShopType> shopTypeList = query().list();
        List<String> stringTypeList = shopTypeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        stringRedisTemplate.opsForList().leftPushAll(redisKey,stringTypeList);
        stringRedisTemplate.expire(redisKey,RedisConstants.CACHE_SHOP_TYPE, TimeUnit.MINUTES);

        return shopTypeList;
    }
}
